import 'package:sinosheets/utils/language/lang_model.dart';
import 'package:sinosheets/utils/isar_manager.dart';
import 'package:isar/isar.dart';
import 'dart:async';

class IsarLangService {
  static final IsarLangService _instance = IsarLangService._internal();
  factory IsarLangService() => _instance;

  Isar? _isar;
  bool _isInitialized = false;

  IsarLangService._internal();

  Future<void> init() async {
    if (_isInitialized && _isar != null) {
      return;
    }

    await IsarManager().init();
    _isar = IsarManager().isar;
    _isInitialized = true;
  }

  /// 保存语言包数据（全部覆盖）
  Future<void> saveLangMap(String locale, Map<String, String> data) async {
    _ensureInitialized();
    await _isar!.writeTxn(() async {
      await _isar!.langModels.filter().localeEqualTo(locale).deleteAll();
      final entries = data.entries.map((e) {
        return LangModel()
          ..locale = locale
          ..key = e.key
          ..value = e.value;
      }).toList();
      await _isar!.langModels.putAll(entries);
    });
  }

  /// 获取整个语言包 map
  Future<Map<String, String>> getLangMap(String locale) async {
    _ensureInitialized();
    final result = await _isar!.langModels.filter().localeEqualTo(locale).findAll();
    return {
      for (var item in result) item.key: item.value,
    };
  }

  /// 获取某个翻译
  Future<String?> getTranslation(String locale, String key) async {
    _ensureInitialized();
    final result = await _isar!.langModels.filter().localeEqualTo(locale).keyEqualTo(key).findFirst();
    return result?.value;
  }

  /// 清除指定语言
  Future<void> clearLocale(String locale) async {
    _ensureInitialized();
    await _isar!.writeTxn(() async {
      await _isar!.langModels.filter().localeEqualTo(locale).deleteAll();
    });
  }

  /// 清除所有
  Future<void> clearAll() async {
    _ensureInitialized();
    await _isar!.writeTxn(() async {
      await _isar!.langModels.clear();
    });
  }

  /// 确保已初始化
  void _ensureInitialized() {
    if (!_isInitialized || _isar == null) {
      throw Exception('IsarLangService未初始化，请先调用init()方法');
    }
  }
}
